package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.entity.vo.DictExcelVo;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/*
    easyexcel回调监听器
 */
@Service
public class DictExcelVoListener extends AnalysisEventListener<DictExcelVo> {
    @Resource
    DictService dictService;
    private List<DictExcelVo> dictExcelVos = new ArrayList<>();
    private int limit = 100;
    @Override
    public void invoke(DictExcelVo data, AnalysisContext context) {
        dictExcelVos.add(data);
        if (dictExcelVos.size()==limit){
            List<Dict> dicts = convertExcelVo2Dicts();
            dictService.saveBatch(dicts);
            dictExcelVos.clear();
        }
    }

    private List<Dict> convertExcelVo2Dicts() {
        List<Dict> dicts = dictExcelVos.stream().map(dictExcelVo -> {//将dictExcelVo对象转为dict对象
            Dict dict = new Dict();
            //将原对象  相同属性名和数据类型的 属性值 拷贝给目标对象
            BeanUtils.copyProperties(dictExcelVo,dict);
            return dict;
        }).filter(dict -> {//筛选dict对象，如果数据库已存在该对象过滤掉
            //如果id已存在  不保存
            return dictService.count(Wrappers.lambdaQuery(Dict.class)
                    .eq(Dict::getId, dict.getId()))==0;
        }).collect(Collectors.toList());
        return dicts;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (dictExcelVos.size()>0){
            List<Dict> dicts = convertExcelVo2Dicts();
            dictService.saveBatch(dicts);
            dictExcelVos.clear();
        }
    }
}
